package ningbo.serializable;

import java.io.*;

/**
 * @Author 宁铂
 * @Date 2021/7/27 11:11
 * @Version 1.0
 */
public class TestSerializable {
    /** 本类用于测试序列化与反序列化
     *  序列化:把程序中的Java对象,永久保存在磁盘中,相当于写出的过程 "out" 对应的序列化流为 :"ObjectOutputStream"
     *  反序列化:把已经序列化的的数据,读取/回复的程序 "in" 对应反序列化的流为:"ObjectInputStream"
     * */

    public static void main(String[] args) {
        method1(); //序列化
        method2(); //反序列化
    }

    private static void method1() {
        ObjectOutputStream out = null;
        try {
            out = new ObjectOutputStream(new FileOutputStream("F:\\TestFile\\1.txt"));

            //对对象进行序列化
            Student student = new Student("海绵宝宝",3,"深海",'男');
            //通过OOS流对象序列化输出Student对象
            out.writeObject(student);
            System.out.println("序列化成功~~~");

        } catch (IOException e) {
            System.out.println("序列化失败~~~");
            e.printStackTrace();
        }finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private static void method2() {
        ObjectInputStream in = null;
        try {
            in = new ObjectInputStream(new FileInputStream("F:\\TestFile\\1.txt"));

            //反序列化
            Object o = in.readObject();

            System.out.println("反序列化成功~~~");
        } catch (Exception e) {
            System.out.println("反序列化失败~~~");
            e.printStackTrace();
        }finally {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
